package com.handpay.zztong.hp.base.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.Volley;
import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.HttpSFTConnector;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.NetEngineListener;
import com.handpay.framework.SSLCustomSocketFactory;
import com.handpay.framework.notice.ApiNoticeFactory;
import com.handpay.framework.notice.ApiNoticeListener;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.NoticeInfo;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.db.ormlite.DataBaseModel;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.notification.activity.NoticeDetailActivity;
import com.handpay.zztong.hp.notification.model.NoticeBody;
import com.handpay.zztong.hp.notification.model.UserNoticesBean;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.utils.PreferenceManager;

import java.io.InputStream;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import se.krka.kahlua.vm.LuaTable;

public class CoreService extends Service implements NetEngineListener {

    public static final String TAG = CoreService.class.getName();
    private static final int IntervalTime_Alarm = 300 * 1000;
    //        	private static final int IntervalTime_Alarm = 5 * 1000;
    private Binder mBinder = new Binder();
    private Timer mTimer;
    private TimerTask mTimerTask;
    /**
     * Notification管理
     */
    public NotificationManager mNotificationManager;
    private DataBaseModel dataBaseModel;

    private void doGetNotices() {
        try {
            AccountUtils.getAccountName(this);
            String userId = AccountUtils.getUserId(CoreService.this);
            String lastUpdateTime = PreferenceManager.getInstance(this.getApplicationContext()).getString(userId, "");
            Hashtable<String, String> params = new Hashtable<String, String>();
            params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
            params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
            params.put(ATProtocolConstant.UPDATETIME, lastUpdateTime);
//            HttpSFTConnector.doVolleyPost(this, requestQueue, ZZTongActivity.Do_GetUserNotices, params, false, 0);
            HttpSFTConnector.doVolleyJsonPost(this, ZZTongActivity.Do_GetUserNotices, UserNoticesBean.class, params, false, 0);
        } catch (Exception e) {
            e.printStackTrace();
//            noticeDB.close();
        }
    }

    @Override
    public void callbackJsonNetResponse(String action, ResponseBean resp, boolean showAlert) {
        if (action.equals(ZZTongActivity.Do_GetUserNotices)) {
            UserNoticesBean userNotices = (UserNoticesBean) resp;
            String lastUpdateTime = userNotices.getLastUpdateTime();
            String userId = AccountUtils.getUserId(CoreService.this);
            PreferenceManager.getInstance(CoreService.this.getApplicationContext()).putString(userId, lastUpdateTime);
            List<NoticeBody> noticeLists = userNotices.getList();
            if (noticeLists != null && noticeLists.size() > 0) {
                for (NoticeBody noticeBody : noticeLists) {
                    noticeBody.setUserId(userId);
                    noticeBody.setLastUpdateTime(lastUpdateTime);
                    dataBaseModel.addNotice(noticeBody);
                }
                HPLog.d(HPLog.SSX_TAG, "排序前:" + noticeLists.toString());
                Collections.sort(noticeLists, new Comparator<NoticeBody>() {
                    @Override
                    public int compare(NoticeBody o1, NoticeBody o2) {//自定义排序规则，时间最大的排序在最前面。
                        try {//NumberFormatException防止服务器返回数据出现问题
                            long l1 = Long.valueOf(o1.getTime());
                            long l2 = Long.valueOf(o2.getTime());
                            if (l1 > l2) {
                                return -1;
                            } else if (l1 < l2) {
                                return 1;
                            } else {
                                return 0;
                            }
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            return 0;
                        }
                    }
                });

                HPLog.d(HPLog.SSX_TAG, "排序后:" + noticeLists.toString());
//              通知栏消息，只有当服务器返回数据的时候才显示最后一条通知消息。
                NoticeBody lastNotice = noticeLists.get(0);
                if (lastNotice != null) {
                    isShowNotice(lastNotice);
                }
            }
            ApiNoticeFactory.getInstance().doBroadCastNotice(ApiNoticeListener.NOTICE_ACTION, null);
        }
    }

    @Override
    public void callbackNetResponse(String action, Hashtable<String, Object> resp, boolean showAlert, boolean dataCompile) {
        if (action.equals(ZZTongActivity.Do_GetUserNotices)) {
            try {
                byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
                if (data == null) {
                    return;
                }
                LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, dataCompile);
                if (luaTable == null) {
                    return;
                }
                String em = (String) luaTable.rawget("errMessage");
                String items = (String) luaTable.rawget("items");
                String lastUpdateTime = (String) luaTable.rawget("lastUpdateTime");
                List<NoticeInfo> infos = NoticeInfo.getNoticeLists(luaTable, items);
//                noticeDB.checkeNoticeInfos(infos, lastUpdateTime);
//                if (noticeDB.isNewNotices()) {
//                    if (!TextUtils.isEmpty(items) && TextUtils.isDigitsOnly(items) && Integer.parseInt(items) > 0) {
//                        NoticeInfo info = noticeDB.getLastTimeNotice();
//                        if (info != null) isShowNotice(info);
//                    }
//                }
                ApiNoticeFactory.getInstance().doBroadCastNotice(ApiNoticeListener.NOTICE_ACTION, null);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } finally {
//                noticeDB.close();
            }
        }
    }

    public class Binder extends android.os.Binder {
        public CoreService getService() {
            return CoreService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        HPLog.i(HPLog.YL_TAG, "onDestroy:");
        if (mTimerTask != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
        clearAllNotify();
        mNotificationManager = null;

    }

    @Override
    public void onCreate() {
        super.onCreate();
        HPLog.i(HPLog.YL_TAG, "onCreate:");
        mTimer = new Timer();
        dataBaseModel = DataBaseModel.getInstance(this);
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                doGetNotices();
            }
        };
        mTimer.schedule(mTimerTask, 0, IntervalTime_Alarm);
        initService();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_REDELIVER_INTENT;
    }

    /**
     * 通知栏显示最新的一条通知
     *
     * @param info 需要显示的通知
     */
    public void isShowNotice(NoticeBody info) {
        mNotificationManager.cancel(100);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
//		//PendingIntent 跳转动作
        Intent intent = new Intent(this, NoticeDetailActivity.class);
        intent.putExtra("noticInfo", info);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setSmallIcon(R.drawable.ic_launcher).setTicker("有最新通知").setContentTitle(info.getTitle()).setContentText(CommonUtils.StringFilter(info.getContent())).setContentIntent(pendingIntent);
        Notification mNotification = mBuilder.build();
        //设置通知  消息  图标
//        mNotification.icon = R.drawable.ic_launcher;
        //在通知栏上点击此通知后自动清除此通知
        mNotification.flags = Notification.FLAG_AUTO_CANCEL;//FLAG_ONGOING_EVENT 在顶部常驻，可以调用下面的清除方法去除  FLAG_AUTO_CANCEL  点击和清理可以去调
        //设置显示通知时的默认的发声、震动、Light效果
        mNotification.defaults = Notification.DEFAULT_VIBRATE;
        //设置发出消息的内容
        mNotification.tickerText = "有最新通知";
        //设置发出通知的时间
        mNotification.when = System.currentTimeMillis();
        mNotification.flags = Notification.FLAG_AUTO_CANCEL; //在通知栏上点击此通知后自动清除此通知
        mNotificationManager.notify(100, mNotification);
    }

    /**
     * 显示他通知栏消息
     *
     * @param info 通知
     */
    public void isShowNotice(NoticeInfo info) {
        mNotificationManager.cancel(100);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
//		//PendingIntent 跳转动作
        Intent intent = new Intent(this, NoticeDetailActivity.class);
        intent.putExtra(ZZTongActivity.NOTICEINFO, info);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setSmallIcon(R.drawable.ic_launcher).setTicker("有最新通知").setContentTitle(info.getTitle()).setContentText(info.getText()).setContentIntent(pendingIntent);
        Notification mNotification = mBuilder.build();
        //设置通知  消息  图标
        mNotification.icon = R.drawable.ic_launcher;
        //在通知栏上点击此通知后自动清除此通知
        mNotification.flags = Notification.FLAG_AUTO_CANCEL;//FLAG_ONGOING_EVENT 在顶部常驻，可以调用下面的清除方法去除  FLAG_AUTO_CANCEL  点击和清理可以去调
        //设置显示通知时的默认的发声、震动、Light效果
        mNotification.defaults = Notification.DEFAULT_VIBRATE;
        //设置发出消息的内容
        mNotification.tickerText = "有最新通知";
        //设置发出通知的时间
        mNotification.when = System.currentTimeMillis();
        mNotification.flags = Notification.FLAG_AUTO_CANCEL; //在通知栏上点击此通知后自动清除此通知
        mNotificationManager.notify(100, mNotification);
    }

    /**
     * 初始化要用到的系统服务
     */
    private void initService() {
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    /**
     * 清除当前创建的通知栏
     */
    public void clearNotify(int notifyId) {
        mNotificationManager.cancel(notifyId);//删除一个特定的通知ID对应的通知
//		mNotification.cancel(getResources().getString(R.string.app_name));
    }

    /**
     * 清除所有通知栏
     */
    public void clearAllNotify() {
        mNotificationManager.cancelAll();// 删除你发的所有通知
    }


}
